package czy.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    /* 加密 */
    private PasswordEncoder encoder = new BCryptPasswordEncoder();

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
         auth.inMemoryAuthentication()
         .withUser("root").password(encoder.encode("123456")).roles("ADMIN","USER")
         .and()
         .passwordEncoder(encoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable();

        /** 为了支持下面的premitAll() */
        http.authorizeRequests();

        http.formLogin()
                /** 登录请求拦截，post表单请求 */
                .usernameParameter("username")
                .passwordParameter("password")
                /** 登录处理url，仅get请求可访问 */
                .loginProcessingUrl("/login")
                /** 成功、失败重定向URL */
                .defaultSuccessUrl("/index")
                .failureUrl("/error")
                /** 登录页面，如果手动配置，需要定制页面
                 * 默认情况下(不配置)使用内部页面
                 */
                //.loginPage("/loginPage")
                .permitAll();
                /** 也可以配置内部转发URL */

        /** 登出配置 */
        http.logout().invalidateHttpSession(true)
                .clearAuthentication(true)
                /** 登出处理的url，get请求可访问 */
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login")
                .permitAll();

        http.httpBasic().disable();
    }
}
